#include "call_screen.h"
#include "smart_home_ui.h"
#include "myfont.h"
#include "mqtt_cloud.h"
#include "device_state_manager.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>

// 全局UI对象
static lv_obj_t *call_screen = NULL;
static lv_obj_t *send_btn = NULL;
static lv_obj_t *hangup_btn = NULL;
static lv_obj_t *status_label = NULL;
static lv_obj_t *contact_btns[4] = {NULL};
static lv_obj_t *contact_labels[4] = {NULL};
static lv_obj_t *contact_avatars[4] = {NULL};

// 联系人数据
static contact_info_t contacts[4] = {
    {"爸爸", "138****1234", "1966732872@qq.com", "", "http://your-server.com/webhook/dad", true},
    {"妈妈", "139****5678", "", "", "http://your-server.com/webhook/mom", true},
    {"儿子", "135****9012", "", "", "http://your-server.com/webhook/son", true},
    {"女儿", "136****3456", "", "", "http://your-server.com/webhook/daughter", true}
};

// 联系人头像映射
static const lv_img_dsc_t* contact_avatars_imgs[4] = {
    &father,    // 爸爸头像
    &mom,       // 妈妈头像  
    &son,       // 儿子头像
    &daughter   // 女儿头像
};

// 云平台配置
typedef struct {
    char api_url[256];          // 云平台API地址
    char api_key[128];          // API密钥
    char device_id[64];         // 设备ID
    char project_name[64];      // 项目名称
    int timeout;                // 超时时间（秒）
} cloud_config_t;

// 默认云平台配置
static cloud_config_t cloud_config = {
    .api_url = "http://localhost:8080/api/messages",  // 使用本地测试服务器
    .api_key = "test_api_key_12345",                  // 测试API密钥
    .device_id = "smart_home_001",                    // 设备唯一标识
    .project_name = "智能家居系统",                    // 项目名称
    .timeout = 10                                     // 10秒超时
};

// 状态管理
static bool call_screen_valid = false;
static int selected_contact = -1;
static message_status_t current_status = MSG_STATUS_IDLE;
static bool is_calling = false;  // 新增：是否正在通话状态

// 持久化状态结构
typedef struct {
    int saved_selected_contact;
    bool saved_is_calling;
} call_persistent_state_t;

static call_persistent_state_t persistent_state = {-1, false};

// 前向声明
static void back_btn_event_cb(lv_event_t *e);
static void contact_btn_event_cb(lv_event_t *e);
static void send_btn_event_cb(lv_event_t *e);
static void hangup_btn_event_cb(lv_event_t *e);
static void save_call_state(void);
static void restore_call_state(void);



// 返回按钮点击事件
static void back_btn_event_cb(lv_event_t *e) {
    if(lv_event_get_code(e) != LV_EVENT_CLICKED) return;
    
    printf("呼叫页面: 保存状态并返回主界面\n");
    save_call_state();  // 保存当前状态
    return_to_smart_home_from_call();
}

// 联系人按钮点击事件
static void contact_btn_event_cb(lv_event_t *e) {
    if(lv_event_get_code(e) != LV_EVENT_CLICKED) return;
    
    // 如果正在通话中，不允许选择其他联系人
    if(is_calling) {
        set_call_status_message("请先挂断当前通话", true);
        return;
    }
    
    lv_obj_t *btn = lv_event_get_target(e);
    
    // 找到被点击的联系人
    for(int i = 0; i < 4; i++) {
        if(contact_btns[i] == btn) {
            selected_contact = i;
            
            // 更新按钮样式显示选中状态（头像不变色）
            for(int j = 0; j < 4; j++) {
                if(j == i) {
                    // 选中状态样式 - 只改变按钮方框
                    lv_obj_set_style_bg_color(contact_btns[j], lv_color_hex(0x3498db), LV_PART_MAIN);
                    lv_obj_set_style_border_color(contact_btns[j], lv_color_hex(0x2980b9), LV_PART_MAIN);
                    lv_obj_set_style_border_width(contact_btns[j], 3, LV_PART_MAIN);
                } else {
                    // 未选中状态样式
                    lv_obj_set_style_bg_color(contact_btns[j], lv_color_hex(0x34495e), LV_PART_MAIN);
                    lv_obj_set_style_border_color(contact_btns[j], lv_color_hex(0x7f8c8d), LV_PART_MAIN);
                    lv_obj_set_style_border_width(contact_btns[j], 1, LV_PART_MAIN);
                }
            }
            
            char status_msg[64];
            snprintf(status_msg, sizeof(status_msg), "已选择: %s", contacts[i].name);
            set_call_status_message(status_msg, false);
            printf("呼叫页面: 选择联系人 %s\n", contacts[i].name);
            break;
        }
    }
}

// 呼叫按钮点击事件
static void send_btn_event_cb(lv_event_t *e) {
    if(lv_event_get_code(e) != LV_EVENT_CLICKED) return;
    
    if(selected_contact < 0 || selected_contact >= 4) {
        set_call_status_message("请先选择联系人", true);
        return;
    }
    
    // 隐藏呼叫按钮，显示挂断按钮
    lv_obj_add_flag(send_btn, LV_OBJ_FLAG_HIDDEN);
    lv_obj_clear_flag(hangup_btn, LV_OBJ_FLAG_HIDDEN);
    
    // 更新选中联系人按钮为绿色，表示正在通话（头像不变色）
    lv_obj_set_style_bg_color(contact_btns[selected_contact], lv_color_hex(0x27ae60), LV_PART_MAIN);
    lv_obj_set_style_border_color(contact_btns[selected_contact], lv_color_hex(0x1e8449), LV_PART_MAIN);
    
    // 简化为直接呼叫，类似于拨打电话
    printf("呼叫页面: 正在呼叫 %s (%s)\n", contacts[selected_contact].name, contacts[selected_contact].phone);
    
    // 检查MQTT连接状态
    mqtt_status_t mqtt_status = mqtt_cloud_get_status();
    if(mqtt_status != MQTT_CONNECTED) {
        // MQTT未连接，给出更详细的错误信息
        const char* status_msg;
        switch(mqtt_status) {
            case MQTT_DISCONNECTED:
                status_msg = "云平台未连接";
                break;
            case MQTT_CONNECTING:
                status_msg = "云平台连接中，请稍后再试";
                break;
            case MQTT_CONNECTION_FAILED:
                status_msg = "云平台连接失败";
                break;
            default:
                status_msg = "网络异常";
                break;
        }
        
        printf("呼叫失败: MQTT状态=%d, %s\n", mqtt_status, status_msg);
        set_call_status_message(status_msg, true);
        
        // 恢复按钮状态
        lv_obj_clear_flag(send_btn, LV_OBJ_FLAG_HIDDEN);
        lv_obj_add_flag(hangup_btn, LV_OBJ_FLAG_HIDDEN);
        
        // 恢复按钮颜色
        lv_obj_set_style_bg_color(contact_btns[selected_contact], lv_color_hex(0x3498db), LV_PART_MAIN);
        lv_obj_set_style_border_color(contact_btns[selected_contact], lv_color_hex(0x2980b9), LV_PART_MAIN);
        return;
    }
    
    // 上传呼叫数据到服务器
    int upload_result = mqtt_upload_call_data(selected_contact, true, NULL);
    
    if(upload_result == 0) {
        printf("呼叫数据上传到服务器成功\n");
        is_calling = true;  // 设置通话状态
        char call_msg[64];
        snprintf(call_msg, sizeof(call_msg), "正在呼叫%s...", contacts[selected_contact].name);
        set_call_status_message(call_msg, false);
    } else {
        printf("呼叫数据上传到服务器失败，错误码: %d\n", upload_result);
        set_call_status_message("呼叫发送失败", true);
        
        // 恢复按钮状态
        lv_obj_clear_flag(send_btn, LV_OBJ_FLAG_HIDDEN);
        lv_obj_add_flag(hangup_btn, LV_OBJ_FLAG_HIDDEN);
        
        // 恢复按钮颜色
        lv_obj_set_style_bg_color(contact_btns[selected_contact], lv_color_hex(0x3498db), LV_PART_MAIN);
        lv_obj_set_style_border_color(contact_btns[selected_contact], lv_color_hex(0x2980b9), LV_PART_MAIN);
        return;
    }
}

// 挂断按钮点击事件
static void hangup_btn_event_cb(lv_event_t *e) {
    if(lv_event_get_code(e) != LV_EVENT_CLICKED) return;
    
    if(selected_contact < 0 || selected_contact >= 4) return;
    
    // 先保存当前联系人索引，因为后面会重置
    int hangup_contact = selected_contact;
    
    // 隐藏挂断按钮，显示呼叫按钮
    lv_obj_add_flag(hangup_btn, LV_OBJ_FLAG_HIDDEN);
    lv_obj_clear_flag(send_btn, LV_OBJ_FLAG_HIDDEN);
    
    // 重置通话状态和选中联系人
    is_calling = false;
    selected_contact = -1;
    
    // 清除持久化状态
    persistent_state.saved_selected_contact = -1;
    persistent_state.saved_is_calling = false;
    
    // 重置所有联系人按钮样式
    for(int i = 0; i < 4; i++) {
        lv_obj_set_style_bg_color(contact_btns[i], lv_color_hex(0x34495e), LV_PART_MAIN);
        lv_obj_set_style_border_width(contact_btns[i], 1, LV_PART_MAIN);
        lv_obj_set_style_border_color(contact_btns[i], lv_color_hex(0x7f8c8d), LV_PART_MAIN);
    }
    
    // 更新状态消息
    set_call_status_message("请选择联系人进行呼叫", false);
    
    // 更新设备状态管理器中对应联系人的呼叫触发器状态为false
    printf("hangup_btn_event_cb: 挂断联系人索引 = %d\n", hangup_contact);
    if(hangup_contact >= 0 && hangup_contact < 4) {
        switch(hangup_contact) {
            case 0: // 爸爸
                printf("hangup_btn_event_cb: 设置爸爸呼叫状态为false\n");
                update_dad_call_triggered(false);
                break;
            case 1: // 妈妈
                printf("hangup_btn_event_cb: 设置妈妈呼叫状态为false\n");
                update_mom_call_triggered(false);
                break;
            case 2: // 儿子
                printf("hangup_btn_event_cb: 设置儿子呼叫状态为false\n");
                update_son_call_triggered(false);
                break;
            case 3: // 女儿
                printf("hangup_btn_event_cb: 设置女儿呼叫状态为false\n");
                update_daughter_call_triggered(false);
                break;
        }
    }
        
        // 上传挂断状态到服务器
        printf("呼叫页面: 正在上传挂断状态...\n");
        int upload_result = mqtt_upload_call_data(hangup_contact, false, NULL);
        if(upload_result == 0) {
            printf("挂断状态上传成功\n");
        } else {
            printf("挂断状态上传失败，错误码: %d\n", upload_result);
        }
        // printf("呼叫页面: 挂断呼叫\n"); // 已注释或移除
    }




// 发送HTTP消息
bool send_http_message(int contact_index, const char *message) {
    if(contact_index < 0 || contact_index >= 4 || !message) {
        return false;
    }
    
    const contact_info_t *contact = &contacts[contact_index];
    if(!contact->enabled) {
        return false;
    }
    
    printf("呼叫页面: 发送消息给 %s: %s\n", contact->name, message);
    
    // 这里实现实际的HTTP发送逻辑
    // 为了演示，使用简单的模拟
    
    // 模拟网络延迟
    sleep(2);
    
    // 简单的成功率模拟（实际项目中替换为真实的HTTP请求）
    bool success = (rand() % 10) > 2; // 80%成功率
    
    if(success) {
        printf("呼叫页面: 消息发送成功\n");
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            lv_label_set_text(status_label, "消息发送成功！");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0x27ae60), LV_PART_MAIN);
        }
    } else {
        printf("呼叫页面: 消息发送失败\n");
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            lv_label_set_text(status_label, "消息发送失败，请重试");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
        }
    }
    
    return success;
}

// 发送消息到云平台
bool send_cloud_message(int contact_index, const char *subject, const char *message) {
    if(contact_index < 0 || contact_index >= 4 || !subject || !message) {
        printf("云平台: 消息发送参数无效\n");
        return false;
    }
    
    const contact_info_t *contact = &contacts[contact_index];
    if(!contact->enabled) {
        printf("云平台: 联系人 %s 未启用\n", contact->name);
        return false;
    }
    
    printf("云平台: 准备发送消息给 %s\n", contact->name);
    printf("消息主题: %s\n", subject);
    printf("消息内容: %s\n", message);
    
    // 解析云平台URL
    char host[128] = {0};
    char path[256] = {0};
    int port = 80;
    
    // 打印当前配置的URL用于调试
    printf("云平台: 当前配置的API URL: %s\n", cloud_config.api_url);
    
    // 简单解析URL (假设格式为 http://host:port/path 或 http://host/path)
    char temp_path[256] = {0};
    int result1 = sscanf(cloud_config.api_url, "http://%127[^:/]:%d/%255s", host, &port, temp_path);
    printf("云平台: 第一次解析结果: %d, host=%s, port=%d, path=%s\n", result1, host, port, temp_path);
    
    if(result1 == 3) {
        // host:port/path 格式
        if (strlen(temp_path) < sizeof(path) - 2) {  // 确保有足够空间添加前缀"/"和终止符
            path[0] = '/';
            strncpy(path + 1, temp_path, sizeof(path) - 2);
            path[sizeof(path) - 1] = '\0';
        } else {
            strncpy(path, "/", sizeof(path) - 1);
            path[sizeof(path) - 1] = '\0';
        }
    } else {
        int result2 = sscanf(cloud_config.api_url, "http://%127[^/]/%255s", host, temp_path);
        printf("云平台: 第二次解析结果: %d, host=%s, path=%s\n", result2, host, temp_path);
        
        if(result2 == 2) {
            // host/path 格式，使用默认端口80
            port = 80;
            if (strlen(temp_path) < sizeof(path) - 2) {  // 确保有足够空间添加前缀"/"和终止符
                path[0] = '/';
                strncpy(path + 1, temp_path, sizeof(path) - 2);
                path[sizeof(path) - 1] = '\0';
            } else {
                strncpy(path, "/", sizeof(path) - 1);
                path[sizeof(path) - 1] = '\0';
            }
        } else {
            int result3 = sscanf(cloud_config.api_url, "http://%127s", host);
            printf("云平台: 第三次解析结果: %d, host=%s\n", result3, host);
            
            if(result3 == 1) {
                // 只有host，使用默认路径
                port = 80;
                strcpy(path, "/api/messages");
            } else {
                printf("云平台: URL格式无效: %s\n", cloud_config.api_url);
                if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
                    lv_label_set_text(status_label, "云平台URL配置错误");
                    lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
                }
                return false;
            }
        }
    }
    
    printf("云平台: 解析完成 - host=%s, port=%d, path=%s\n", host, port, path);
    
    // 获取当前时间
    time_t now = time(NULL);
    struct tm *local_time = localtime(&now);
    char time_str[64];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", local_time);
    
    // 构建JSON格式的消息内容
    char *json_content = malloc(2048);
    if(!json_content) {
        printf("云平台: 分配JSON内容缓冲区失败\n");
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            lv_label_set_text(status_label, "内存分配失败");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
        }
        return false;
    }
    
    snprintf(json_content, 2048,
        "{\n"
        "  \"device_id\": \"%s\",\n"
        "  \"project_name\": \"%s\",\n"
        "  \"timestamp\": \"%s\",\n"
        "  \"recipient\": {\n"
        "    \"name\": \"%s\",\n"
        "    \"phone\": \"%s\"\n"
        "  },\n"
        "  \"message\": {\n"
        "    \"subject\": \"%s\",\n"
        "    \"content\": \"%s\",\n"
        "    \"type\": \"smart_home_notification\"\n"
        "  },\n"
        "  \"source\": {\n"
        "    \"system\": \"智能家居系统\",\n"
        "    \"version\": \"v1.0\",\n"
        "    \"module\": \"呼叫通知\"\n"
        "  }\n"
        "}",
        cloud_config.device_id, cloud_config.project_name, time_str,
        contact->name, contact->phone, subject, message);
    
    // 使用HTTP POST发送到云平台
    int sockfd;
    struct sockaddr_in server_addr;
    struct hostent *server;
    
    // 创建socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0) {
        printf("云平台: 创建socket失败\n");
        free(json_content);
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            lv_label_set_text(status_label, "网络连接失败");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
        }
        return false;
    }
    
    // 设置超时
    struct timeval timeout;
    timeout.tv_sec = cloud_config.timeout;
    timeout.tv_usec = 0;
    setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
    setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
    
    // 获取主机信息
    server = gethostbyname(host);
    if(server == NULL) {
        printf("云平台: 无法解析主机: %s\n", host);
        close(sockfd);
        free(json_content);
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            lv_label_set_text(status_label, "无法连接云平台");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
        }
        return false;
    }
    
    // 设置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    memcpy(&server_addr.sin_addr.s_addr, server->h_addr, server->h_length);
    
    // 连接到服务器
    if(connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        printf("云平台: 连接 %s:%d 失败\n", host, port);
        close(sockfd);
        free(json_content);
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            lv_label_set_text(status_label, "云平台连接失败");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
        }
        return false;
    }
    
    // 构建HTTP POST请求
    char *http_request = malloc(4096);
    if(!http_request) {
        printf("云平台: 分配请求缓冲区失败\n");
        close(sockfd);
        free(json_content);
        return false;
    }
    
    snprintf(http_request, 4096,
        "POST %s HTTP/1.1\r\n"
        "Host: %s:%d\r\n"
        "Content-Type: application/json\r\n"
        "Content-Length: %zu\r\n"
        "Authorization: Bearer %s\r\n"
        "User-Agent: SmartHome/1.0\r\n"
        "Connection: close\r\n"
        "\r\n"
        "%s",
        path, host, port, strlen(json_content), cloud_config.api_key, json_content);
    
    // 发送HTTP请求
    if(send(sockfd, http_request, strlen(http_request), 0) < 0) {
        printf("云平台: 发送请求失败\n");
        close(sockfd);
        free(json_content);
        free(http_request);
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            lv_label_set_text(status_label, "发送请求失败");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
        }
        return false;
    }
    
    // 接收响应
    char response[1024] = {0};
    int bytes_received = recv(sockfd, response, sizeof(response) - 1, 0);
    
    // 清理资源
    close(sockfd);
    free(json_content);
    free(http_request);
    
    bool result = false;
    if(bytes_received > 0) {
        response[bytes_received] = '\0';
        printf("云平台响应: %s\n", response);
        
        // 检查HTTP状态码
        if(strstr(response, "200 OK") != NULL) {
            result = true;
        }
    }
    
    // 检查发送结果
    if(result) {
        printf("云平台: 消息发送成功给 %s\n", contact->name);
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            char success_msg[128];
            snprintf(success_msg, sizeof(success_msg), "消息已发送给%s", contact->name);
            lv_label_set_text(status_label, success_msg);
            lv_obj_set_style_text_color(status_label, lv_color_hex(0x27ae60), LV_PART_MAIN);
        }
        
        // 更新设备状态管理器中的呼叫触发器状态
        switch(contact_index) {
            case 0: // 爸爸
                update_dad_call_triggered(true);
                break;
            case 1: // 妈妈
                update_mom_call_triggered(true);
                break;
            case 2: // 儿子
                update_son_call_triggered(true);
                break;
            case 3: // 女儿
                update_daughter_call_triggered(true);
                break;
        }
        
        return true;
    } else {
        printf("云平台: 消息发送失败\n");
        if(call_screen_valid && status_label && lv_obj_is_valid(status_label)) {
            lv_label_set_text(status_label, "云平台发送失败");
            lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
        }
        return false;
    }
}

// 设置状态消息
void set_call_status_message(const char *message, bool is_error) {
    if(!call_screen_valid || !status_label || !lv_obj_is_valid(status_label)) {
        return;
    }
    
    lv_label_set_text(status_label, message);
    if(is_error) {
        lv_obj_set_style_text_color(status_label, lv_color_hex(0xe74c3c), LV_PART_MAIN);
    } else {
        lv_obj_set_style_text_color(status_label, lv_color_hex(0x3498db), LV_PART_MAIN);
    }
}

// 保存呼叫状态
static void save_call_state(void) {
    persistent_state.saved_selected_contact = selected_contact;
    persistent_state.saved_is_calling = is_calling;
    
    printf("呼叫页面: 保存状态 - 选中联系人=%d, 通话状态=%s\n", 
           selected_contact, is_calling ? "true" : "false");
}

// 恢复呼叫状态
static void restore_call_state(void) {
    if(!call_screen_valid) return;
    
    // 恢复选中的联系人
    if(persistent_state.saved_selected_contact >= 0 && persistent_state.saved_selected_contact < 4) {
        selected_contact = persistent_state.saved_selected_contact;
        
        // 更新联系人按钮的选中状态
        for(int i = 0; i < 4; i++) {
            if(i == selected_contact) {
                if(persistent_state.saved_is_calling) {
                    // 恢复通话状态
                    lv_obj_set_style_bg_color(contact_btns[i], lv_color_hex(0x27ae60), LV_PART_MAIN);
                    lv_obj_set_style_border_color(contact_btns[i], lv_color_hex(0x1e8449), LV_PART_MAIN);
                    lv_obj_set_style_border_width(contact_btns[i], 3, LV_PART_MAIN);
                } else {
                    // 恢复选中但未通话状态
                    lv_obj_set_style_bg_color(contact_btns[i], lv_color_hex(0x3498db), LV_PART_MAIN);
                    lv_obj_set_style_border_color(contact_btns[i], lv_color_hex(0x2980b9), LV_PART_MAIN);
                    lv_obj_set_style_border_width(contact_btns[i], 3, LV_PART_MAIN);
                }
            } else {
                // 未选中状态
                lv_obj_set_style_bg_color(contact_btns[i], lv_color_hex(0x34495e), LV_PART_MAIN);
                lv_obj_set_style_border_color(contact_btns[i], lv_color_hex(0x7f8c8d), LV_PART_MAIN);
                lv_obj_set_style_border_width(contact_btns[i], 1, LV_PART_MAIN);
            }
        }
    }
    
    // 恢复通话状态
    if(persistent_state.saved_is_calling) {
        is_calling = true;
        
        // 隐藏呼叫按钮，显示挂断按钮
        if(send_btn && lv_obj_is_valid(send_btn)) {
            lv_obj_add_flag(send_btn, LV_OBJ_FLAG_HIDDEN);
        }
        if(hangup_btn && lv_obj_is_valid(hangup_btn)) {
            lv_obj_clear_flag(hangup_btn, LV_OBJ_FLAG_HIDDEN);
        }
        
        // 显示通话状态
        if(selected_contact >= 0 && selected_contact < 4) {
            char call_msg[64];
            snprintf(call_msg, sizeof(call_msg), "正在呼叫%s...", contacts[selected_contact].name);
            set_call_status_message(call_msg, false);
        }
    } else {
        is_calling = false;
        
        // 显示呼叫按钮，隐藏挂断按钮
        if(send_btn && lv_obj_is_valid(send_btn)) {
            lv_obj_clear_flag(send_btn, LV_OBJ_FLAG_HIDDEN);
        }
        if(hangup_btn && lv_obj_is_valid(hangup_btn)) {
            lv_obj_add_flag(hangup_btn, LV_OBJ_FLAG_HIDDEN);
        }
        
        // 显示选中状态或默认状态
        if(selected_contact >= 0 && selected_contact < 4) {
            char status_msg[64];
            snprintf(status_msg, sizeof(status_msg), "已选择: %s", contacts[selected_contact].name);
            set_call_status_message(status_msg, false);
        } else {
            set_call_status_message("请选择联系人进行呼叫", false);
        }
    }
    
    printf("呼叫页面: 恢复状态 - 选中联系人=%d, 通话状态=%s\n", 
           selected_contact, is_calling ? "true" : "false");
}

// 创建呼叫页面
void create_call_screen(void) {
    // 清理之前的界面
    cleanup_call_screen();
    
    // 强制清除屏幕残影
    force_clear_screen_ghosting();
    
    // 创建屏幕
    call_screen = lv_obj_create(NULL);
    lv_obj_set_style_bg_color(call_screen, lv_color_hex(0x2c3e50), LV_PART_MAIN);
    lv_obj_set_style_bg_opa(call_screen, LV_OPA_COVER, LV_PART_MAIN);
    lv_obj_clear_flag(call_screen, LV_OBJ_FLAG_SCROLLABLE);
    
    call_screen_valid = true;
    
    // 创建顶部控制栏
    lv_obj_t *top_bar = lv_obj_create(call_screen);
    lv_obj_set_size(top_bar, lv_pct(100), 60);
    lv_obj_align(top_bar, LV_ALIGN_TOP_MID, 0, 0);
    lv_obj_set_style_bg_color(top_bar, lv_color_hex(0x34495e), LV_PART_MAIN);
    lv_obj_set_style_border_width(top_bar, 0, LV_PART_MAIN);
    lv_obj_set_style_radius(top_bar, 0, LV_PART_MAIN);
    lv_obj_clear_flag(top_bar, LV_OBJ_FLAG_SCROLLABLE);
    
    // 返回按钮
    lv_obj_t *back_btn = lv_btn_create(top_bar);
    lv_obj_set_size(back_btn, 80, 40);
    lv_obj_align(back_btn, LV_ALIGN_LEFT_MID, 10, 0);
    lv_obj_add_event_cb(back_btn, back_btn_event_cb, LV_EVENT_CLICKED, NULL);
    lv_obj_set_style_bg_color(back_btn, lv_color_hex(0xe74c3c), LV_PART_MAIN);
    lv_obj_set_style_border_width(back_btn, 0, LV_PART_MAIN);
    lv_obj_set_style_radius(back_btn, 8, LV_PART_MAIN);
    
    lv_obj_t *back_label = lv_label_create(back_btn);
    lv_label_set_text(back_label, LV_SYMBOL_LEFT " 返回");
    lv_obj_set_style_text_font(back_label, &lv_font_source_han_sans_bold_20, 0);
    lv_obj_set_style_text_color(back_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_center(back_label);
    
    // 标题
    lv_obj_t *title_label = lv_label_create(top_bar);
    lv_label_set_text(title_label, LV_SYMBOL_CALL " 一键呼叫");
    lv_obj_set_style_text_font(title_label, &lv_font_source_han_sans_bold_20, 0);
    lv_obj_set_style_text_color(title_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_center(title_label);
    
    // 创建主容器 - 重新设计为居中布局
    lv_obj_t *main_container = lv_obj_create(call_screen);
    lv_obj_set_size(main_container, lv_pct(80), 450);
    lv_obj_align(main_container, LV_ALIGN_CENTER, 0, 30);
    lv_obj_set_style_bg_color(main_container, lv_color_hex(0x34495e), LV_PART_MAIN);
    lv_obj_set_style_border_width(main_container, 0, LV_PART_MAIN);
    lv_obj_set_style_radius(main_container, 15, LV_PART_MAIN);
    lv_obj_set_style_pad_all(main_container, 20, LV_PART_MAIN);
    lv_obj_clear_flag(main_container, LV_OBJ_FLAG_SCROLLABLE);
    
    // 呼叫控制区域
    lv_obj_t *control_panel = lv_obj_create(main_container);
    lv_obj_set_size(control_panel, lv_pct(100), 80);
    lv_obj_align(control_panel, LV_ALIGN_TOP_MID, 0, 0);
    lv_obj_set_style_bg_color(control_panel, lv_color_hex(0x2c3e50), LV_PART_MAIN);
    lv_obj_set_style_border_width(control_panel, 1, LV_PART_MAIN);
    lv_obj_set_style_border_color(control_panel, lv_color_hex(0x7f8c8d), LV_PART_MAIN);
    lv_obj_set_style_radius(control_panel, 10, LV_PART_MAIN);
    lv_obj_set_style_pad_all(control_panel, 15, LV_PART_MAIN);
    lv_obj_clear_flag(control_panel, LV_OBJ_FLAG_SCROLLABLE);
    
    // 呼叫按钮
    send_btn = lv_btn_create(control_panel);
    lv_obj_set_size(send_btn, 120, 50);
    lv_obj_align(send_btn, LV_ALIGN_LEFT_MID, 0, 0);
    lv_obj_add_event_cb(send_btn, send_btn_event_cb, LV_EVENT_CLICKED, NULL);
    lv_obj_set_style_bg_color(send_btn, lv_color_hex(0x27ae60), LV_PART_MAIN);
    lv_obj_set_style_border_width(send_btn, 0, LV_PART_MAIN);
    lv_obj_set_style_radius(send_btn, 8, LV_PART_MAIN);
    
    lv_obj_t *send_label = lv_label_create(send_btn);
    lv_label_set_text(send_label, LV_SYMBOL_CALL " 呼叫");
    lv_obj_set_style_text_font(send_label, &lv_font_source_han_sans_bold_20, 0);
    lv_obj_set_style_text_color(send_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_center(send_label);
    
    // 挂断按钮
    hangup_btn = lv_btn_create(control_panel);
    lv_obj_set_size(hangup_btn, 120, 50);
    lv_obj_align(hangup_btn, LV_ALIGN_RIGHT_MID, 0, 0);
    lv_obj_add_event_cb(hangup_btn, hangup_btn_event_cb, LV_EVENT_CLICKED, NULL);
    lv_obj_set_style_bg_color(hangup_btn, lv_color_hex(0xe74c3c), LV_PART_MAIN);
    lv_obj_set_style_border_width(hangup_btn, 0, LV_PART_MAIN);
    lv_obj_set_style_radius(hangup_btn, 8, LV_PART_MAIN);
    lv_obj_add_flag(hangup_btn, LV_OBJ_FLAG_HIDDEN); // 初始隐藏挂断按钮
    
    lv_obj_t *hangup_label = lv_label_create(hangup_btn);
    lv_label_set_text(hangup_label, LV_SYMBOL_CLOSE " 挂断");
    lv_obj_set_style_text_font(hangup_label, &lv_font_source_han_sans_bold_20, 0);
    lv_obj_set_style_text_color(hangup_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_center(hangup_label);
    
    // 状态标签
    status_label = lv_label_create(control_panel);
    lv_label_set_text(status_label, "请选择联系人进行呼叫");
    lv_obj_set_style_text_font(status_label, &lv_font_source_han_sans_bold_20, 0);
    lv_obj_set_style_text_color(status_label, lv_color_hex(0x95a5a6), 0);
    lv_obj_align(status_label, LV_ALIGN_CENTER, 0, 0);
    
    // 联系人区域
    lv_obj_t *contact_panel = lv_obj_create(main_container);
    lv_obj_set_size(contact_panel, lv_pct(100), 320);
    lv_obj_align_to(contact_panel, control_panel, LV_ALIGN_OUT_BOTTOM_MID, 0, 20);
    lv_obj_set_style_bg_color(contact_panel, lv_color_hex(0x2c3e50), LV_PART_MAIN);
    lv_obj_set_style_border_width(contact_panel, 1, LV_PART_MAIN);
    lv_obj_set_style_border_color(contact_panel, lv_color_hex(0x7f8c8d), LV_PART_MAIN);
    lv_obj_set_style_radius(contact_panel, 10, LV_PART_MAIN);
    lv_obj_set_style_pad_all(contact_panel, 20, LV_PART_MAIN);
    lv_obj_clear_flag(contact_panel, LV_OBJ_FLAG_SCROLLABLE);
    
    // 联系人标题
    lv_obj_t *contact_title = lv_label_create(contact_panel);
    lv_label_set_text(contact_title, LV_SYMBOL_SETTINGS " 选择联系人");
    lv_obj_set_style_text_font(contact_title, &lv_font_source_han_sans_bold_20, 0);
    lv_obj_set_style_text_color(contact_title, lv_color_hex(0xFFFFFF), 0);
    lv_obj_align(contact_title, LV_ALIGN_TOP_MID, 0, 0);
    
    // 创建四个联系人按钮 (2x2 布局，优化间距和大小)
    int btn_width = 220;
    int btn_height = 100;
    int spacing_x = 30;
    int spacing_y = 20;
    int start_y = 40;
    
    // 计算居中起始位置
    int total_width = btn_width * 2 + spacing_x;
    int start_x = (lv_obj_get_width(contact_panel) - total_width) / 2;
    
    for(int i = 0; i < 4; i++) {
        int row = i / 2;
        int col = i % 2;
        
        // 联系人按钮
        contact_btns[i] = lv_btn_create(contact_panel);
        lv_obj_set_size(contact_btns[i], btn_width, btn_height);
        lv_obj_set_pos(contact_btns[i], 
                      start_x + col * (btn_width + spacing_x), 
                      start_y + row * (btn_height + spacing_y));
        lv_obj_add_event_cb(contact_btns[i], contact_btn_event_cb, LV_EVENT_CLICKED, NULL);
        lv_obj_set_style_bg_color(contact_btns[i], lv_color_hex(0x34495e), LV_PART_MAIN);
        lv_obj_set_style_border_width(contact_btns[i], 1, LV_PART_MAIN);
        lv_obj_set_style_border_color(contact_btns[i], lv_color_hex(0x7f8c8d), LV_PART_MAIN);
        lv_obj_set_style_radius(contact_btns[i], 12, LV_PART_MAIN);
        lv_obj_set_style_shadow_width(contact_btns[i], 10, LV_PART_MAIN);
        lv_obj_set_style_shadow_color(contact_btns[i], lv_color_black(), LV_PART_MAIN);
        lv_obj_set_style_shadow_opa(contact_btns[i], LV_OPA_20, LV_PART_MAIN);
        
        // 头像图片
        contact_avatars[i] = lv_img_create(contact_btns[i]);
        lv_img_set_src(contact_avatars[i], contact_avatars_imgs[i]);
        lv_obj_set_size(contact_avatars[i], 70, 70);
        lv_obj_align(contact_avatars[i], LV_ALIGN_LEFT_MID, 15, 0);
        
        // 设置头像样式
        lv_obj_set_style_radius(contact_avatars[i], 35, LV_PART_MAIN); // 圆形头像
        lv_obj_set_style_clip_corner(contact_avatars[i], true, LV_PART_MAIN);
        lv_obj_set_style_border_width(contact_avatars[i], 2, LV_PART_MAIN);
        lv_obj_set_style_border_color(contact_avatars[i], lv_color_hex(0xFFFFFF), LV_PART_MAIN);
        lv_obj_set_style_border_opa(contact_avatars[i], LV_OPA_30, LV_PART_MAIN);
        
        // 联系人姓名标签 - 直接放在按钮上，居中显示
        contact_labels[i] = lv_label_create(contact_btns[i]);
        lv_label_set_text(contact_labels[i], contacts[i].name);
        lv_obj_set_style_text_font(contact_labels[i], &lv_font_source_han_sans_bold_20, 0);
        lv_obj_set_style_text_color(contact_labels[i], lv_color_hex(0xFFFFFF), 0);
        lv_obj_align(contact_labels[i], LV_ALIGN_RIGHT_MID, -20, 0);
    }
    
    // 使用动画加载屏幕
    lv_scr_load_anim(call_screen, LV_SCR_LOAD_ANIM_FADE_ON, 300, 0, false);
    
    // 恢复之前保存的状态
    restore_call_state();
    
    printf("呼叫页面: 界面创建完成\n");
}

// 清理呼叫页面
void cleanup_call_screen(void) {
    call_screen_valid = false;
    selected_contact = -1;
    current_status = MSG_STATUS_IDLE;
    is_calling = false;  // 重置通话状态
    
    // 清理UI对象指针
    call_screen = NULL;
    send_btn = NULL;
    hangup_btn = NULL;
    status_label = NULL;
    
    for(int i = 0; i < 4; i++) {
        contact_btns[i] = NULL;
        contact_labels[i] = NULL;
        contact_avatars[i] = NULL;
    }
    
    printf("呼叫页面: 资源清理完成\n");
}

// 返回到智能家居主界面
void return_to_smart_home_from_call(void) {
    cleanup_call_screen();
    return_to_smart_home_ui();
}

// 设置联系人信息
void set_contact_info(int index, const char *name, const char *phone, const char *webhook_url) {
    if(index < 0 || index >= 4) return;
    
    if(name) strncpy(contacts[index].name, name, sizeof(contacts[index].name) - 1);
    if(phone) strncpy(contacts[index].phone, phone, sizeof(contacts[index].phone) - 1);
    if(webhook_url) strncpy(contacts[index].webhook_url, webhook_url, sizeof(contacts[index].webhook_url) - 1);
    
    // 更新UI显示
    if(call_screen_valid && contact_labels[index] && lv_obj_is_valid(contact_labels[index])) {
        lv_label_set_text(contact_labels[index], contacts[index].name);
    }
}

// 获取联系人信息
const contact_info_t* get_contact_info(int index) {
    if(index < 0 || index >= 4) return NULL;
    return &contacts[index];
}

// 设置云平台配置
void set_cloud_config(const char *api_url, const char *api_key, const char *device_id, 
                     const char *project_name, int timeout) {
    if(api_url) strncpy(cloud_config.api_url, api_url, sizeof(cloud_config.api_url) - 1);
    if(api_key) strncpy(cloud_config.api_key, api_key, sizeof(cloud_config.api_key) - 1);
    if(device_id) strncpy(cloud_config.device_id, device_id, sizeof(cloud_config.device_id) - 1);
    if(project_name) strncpy(cloud_config.project_name, project_name, sizeof(cloud_config.project_name) - 1);
    if(timeout > 0) cloud_config.timeout = timeout;
    
    printf("云平台配置已更新: %s, 设备ID: %s, 项目: %s\n", 
           cloud_config.api_url, cloud_config.device_id, cloud_config.project_name);
}
